package top.wshape1.shiziapi.gateway.security;

import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Lazy;
import org.springframework.security.authentication.ReactiveAuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextImpl;
import org.springframework.security.web.server.context.ServerSecurityContextRepository;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;
import top.wshape1.shiziapi.common.domain.CommonUser;
import top.wshape1.shiziapi.gateway.domain.LoginUser;

/**
 * @author Wshape1
 * @version 1.0
 * @description
 * @since 2023-08-24
 */

@Component
@Slf4j
public class SecurityContextRepository implements ServerSecurityContextRepository {

    @Override
    public Mono<Void> save(ServerWebExchange exchange, SecurityContext context) {
        return Mono.empty();
    }

    @Override
    public Mono<SecurityContext> load(ServerWebExchange exchange) {
        log.info("SecurityContextRepository 我来了");
        CommonUser user = exchange.getAttribute("user");

        // 还未登录
        if (user == null)
            return Mono.empty();

        LoginUser loginUser = new LoginUser(user);

        Authentication authentication = new UsernamePasswordAuthenticationToken(loginUser, null, loginUser.getAuthorities());


        // 不需要认证之间存入上下文中
        return Mono.just(authentication)
                .map(SecurityContextImpl::new);
    }
}
